// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/ftx/symbology/currency.h"

namespace coin2::exchange::ftx::symbology {

class FtxProduct : public base::symbology::SpotProduct<FtxCurrency, FtxProduct>,
                   public base::symbology::ProductFromStrMixin<FtxProduct> {
 public:
  using BaseProduct = SpotProduct<FtxCurrency, FtxProduct>;

  using ExchangeType = base::market::ExchangeType;
  using MarketType = base::market::MarketType;
  using CurrencyT = FtxCurrency;
  static const ExchangeType kExchange = ExchangeType::Ftx;
  static const MarketType kMarketType = MarketType::Spot;

 public:
  FtxProduct(const FtxCurrency& base, const FtxCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToFtxNativeProduct(base, quote),
            ToFtxNativeProduct(base, quote),
            base::market::ExchangeType::Ftx) {}

 public:
  static std::unique_ptr<FtxProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<FtxCurrency> base_ptr;
    std::unique_ptr<FtxCurrency> quote_ptr;
    bool success = ParseFtxNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<FtxProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseFtxNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<FtxCurrency>* base_ptr,
      std::unique_ptr<FtxCurrency>* quote_ptr) {
    using base::market::MarketType;

    // TODO(leon): Verify if valid base, quote.
    std::vector<std::string> splitted;
    splitted = Split(product_str, "/");
    if (splitted.size() != 2) {
      return false;
    }

    *base_ptr = FtxCurrency::FromNativeStrNoThrow(splitted[0], resolve_timestamp);
    *quote_ptr = FtxCurrency::FromNativeStrNoThrow(splitted[1], resolve_timestamp);
    if (*base_ptr && *quote_ptr) {
      return true;
    } else {
      return false;
    }
  }

  static std::string ToFtxNativeProduct(const FtxCurrency& base, const FtxCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << '/' << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};

}  // namespace coin2::exchange::ftx::symbology
